import { AllHTMLAttributes, memo } from "react";
import AuthFlowStyle from "./style";
import { Button, Form, Input, Toast } from "antd-mobile";
import { useFetch_login, useFetch_register } from "../../service/login";
import { CheckOutline, CloseOutline } from "antd-mobile-icons";
import { AUTH_TOKEN } from "../../constant";
import { useNavigate } from "react-router-dom";
import { routeItmeType } from "../../router";

interface IProps {
  isLogin: boolean;
  switchClick: (isLogin: boolean) => void;
}

interface fromItemtype {
  account: string;
  password: string;
  password_verify?: string;
}

const AuthFlow = memo((props: IProps & AllHTMLAttributes<HTMLDivElement>) => {
  const { isLogin, switchClick, className, style } = props;
  const nav = useNavigate();

  const { register, registerLoding } = useFetch_register();
  const { login, loginLoading } = useFetch_login();

  const [form] = Form.useForm();

  const password_verify = (_: any, value: string) => {
    const values = form.getFieldsValue() as fromItemtype;
    if (values.password === value) {
      return Promise.resolve();
    }
    return Promise.reject(new Error("两次密码未相同"));
  };

  // 提交表单
  const btnClick = async () => {
    try {
      await form.validateFields();
      const { account, password } = form.getFieldsValue() as fromItemtype;
      // 注册
      if (!isLogin) {
        const res = await register(account, password);
        if (!res.code) {
          Toast.show({
            icon: <CloseOutline />,
            content: res.message,
          });
        } else {
          Toast.show({
            icon: <CheckOutline />,
            content: "注册成功！",
          });
          switchClick(!isLogin);
          form.resetFields();
        }
      }
      // 登录
      else {
        const res = await login(account, password);
        if (!res.code) {
          Toast.show({
            icon: <CloseOutline />,
            content: res.message,
          });
        } else {
          Toast.show({
            icon: <CheckOutline />,
            content: "登录成功!",
          });
          localStorage.setItem(AUTH_TOKEN, res.data);
          nav(`/${routeItmeType.HOME}`);
        }
      }
    } catch (err) {
      console.log(err);
      Toast.show({
        icon: <CloseOutline />,
        content: "表单验证未通过，请检查",
      });
    }
  };

  return (
    <AuthFlowStyle className={className} style={style}>
      <div className="form">
        <Form layout="horizontal" hasFeedback form={form}>
          <Form.Item
            label="用户名"
            name="account"
            rules={[
              { required: true, message: "用户名不能为空" },
              {
                max: 8,
                min: 2,
                message: "长度应为2 ~ 8",
              },
            ]}
          >
            <Input placeholder="请输入用户名" clearable />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              { required: true, message: "密码不能为空" },
              {
                max: 12,
                min: 4,
                message: "长度应为4 ~ 12",
              },
            ]}
          >
            <Input placeholder="请输入密码" clearable type="password" />
          </Form.Item>
          {!isLogin && (
            <Form.Item
              label="确认密码"
              name="password_verify"
              rules={[
                { required: true, message: "二次确认密码不能为空" },
                { validator: password_verify },
              ]}
            >
              <Input
                placeholder="请输入二次确认密码"
                clearable
                type="password"
              />
            </Form.Item>
          )}
        </Form>
        <div
          className="register"
          onClick={() => {
            switchClick(!isLogin);
            form.resetFields();
          }}
        >
          {isLogin ? "立即注册" : "返回登录"}
        </div>
        <Button
          className="submit"
          onClick={btnClick}
          loading={registerLoding || loginLoading}
        >
          {isLogin ? "登录" : "立即注册"}
        </Button>
      </div>
    </AuthFlowStyle>
  );
});

export default AuthFlow;
